package com.clever.auth.shiro;

import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.Objects;

/**
 * @author ChenWang
 * @date 2020/12/14 20:43
 * @since JDK 1.8
 */
public class ShiroRedisSessionManager extends DefaultWebSessionManager {

    private static final String AUTHORIZATION = "Authorization";
    public static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        //获取请求头，或者请求参数中的Token
        String id = StringUtils.isEmpty(WebUtils.toHttp(request).getHeader(AUTHORIZATION)) ?
                request.getParameter(AUTHORIZATION) : WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        //判断id是否为空，如果有则配置对应参数，如果没有，表示是第一次登录，使用框架默认的策略(猜测底层掉了DAO生成了jsessionID)
        //StringUtils.isNonBlank(str); 空串，空串组成的长串都会进行判定
        //StringUtils.isNoneEmpty(str); 只判定长度为0和是否为null
        if (StringUtils.isNoneBlank(id)) {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            //需要认证
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id;
        } else {
            //第一次登录，通过框架生成ID并进行处理
            return super.getSessionId(request, response);
        }
    }

    /**
     * 获取Session 优化单次请求需要多次访问redis的问题
     */
    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        Serializable sessionId = getSessionId(sessionKey);

        ServletRequest request = null;

        // 如果是webSession就获取对应的请求并且做相应的处理
        if(sessionKey instanceof WebSessionKey){
            request = ((WebSessionKey)sessionKey).getServletRequest();
        }
        if(Objects.nonNull(request)&&Objects.nonNull(sessionId)){
            Object sessionObj = request.getAttribute(sessionId.toString());
            if (Objects.nonNull(sessionObj)) {
                return (Session) sessionObj;
            }
        }
        //如果不是WebSession就通过父类方法获取Session
        Session session = super.retrieveSession(sessionKey);
        if (Objects.nonNull(session)&&Objects.nonNull(sessionId)) {
            session.setAttribute(sessionId.toString(), session);
        }
        return session;
    }
}
